library(tidyr)
library(ggplot2)
library(corrplot)
## corrplot 0.84 loaded
library(GGally)
library(MASS)
data("Boston")
str(Boston)
## 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
summary(Boston)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
According to the structure of the data, Boston dataset, which is already loaded in R, has 506 observattions (rows) and 14 variables (columns). The data are mainly gathered to understand the effect of housing values in suburbs of Boston on different vairbles such as crime rate.
pairs(Boston)
The plot above shows the correlations of all the variables in the dataset. But let’s look at a more advanced plot to see the distribution of the data as well as correlation of the variables.
p <- ggpairs(Boston, mapping = aes(alpha = 0.3), lower = list(combo = wrap("facethist", bins = 20)))
p
The above plot demonstrates the distribution of the data as well as the correlations of the variables. As an example, data in the variable “rm”, average number of room per dwelling, have normal distribution, and there is a positive, and rather strong, correlation between “zn” (proportion of residential land zoned for lots over 25,000 sq.ft.), and “dis” (weighted mean of distances to five Boston employment centres).
But we can look at the corraltions with more r funcations. Let’s explore cor_matrix function, which provides handy, easy-to-interpret-correlation matrix.
cor_matrix<-cor(Boston) %>% round(digit=2)
cor_matrix %>% round(cor_matrix)
## crim zn indus chas nox rm age dis rad tax ptratio black lstat
## crim 1.0 0.0 0.0 0 0.0 0.0 0.0 0.0 0.6 0.6 0 0 0.0
## zn 0.0 1.0 0.0 0 0.0 0.0 0.0 0.7 0.0 0.0 0 0 0.0
## indus 0.0 0.0 1.0 0 0.8 0.0 0.6 0.0 0.6 0.7 0 0 0.6
## chas 0.0 0.0 0.0 1 0.0 0.0 0.0 0.0 0.0 0.0 0 0 0.0
## nox 0.0 0.0 0.8 0 1.0 0.0 0.7 0.0 0.6 0.7 0 0 0.6
## rm 0.0 0.0 0.0 0 0.0 1.0 0.0 0.0 0.0 0.0 0 0 0.0
## age 0.0 0.0 0.6 0 0.7 0.0 1.0 0.0 0.0 0.5 0 0 0.6
## dis 0.0 0.7 0.0 0 0.0 0.0 0.0 1.0 0.0 0.0 0 0 0.0
## rad 0.6 0.0 0.6 0 0.6 0.0 0.0 0.0 1.0 0.9 0 0 0.0
## tax 0.6 0.0 0.7 0 0.7 0.0 0.5 0.0 0.9 1.0 0 0 0.5
## ptratio 0.0 0.0 0.0 0 0.0 0.0 0.0 0.0 0.0 0.0 1 0 0.0
## black 0.0 0.0 0.0 0 0.0 0.0 0.0 0.0 0.0 0.0 0 1 0.0
## lstat 0.0 0.0 0.6 0 0.6 0.0 0.6 0.0 0.0 0.5 0 0 1.0
## medv 0.0 0.0 0.0 0 0.0 0.7 0.0 0.0 0.0 0.0 0 0 0.0
## medv
## crim 0.0
## zn 0.0
## indus 0.0
## chas 0.0
## nox 0.0
## rm 0.7
## age 0.0
## dis 0.0
## rad 0.0
## tax 0.0
## ptratio 0.0
## black 0.0
## lstat 0.0
## medv 1.0
corrplot(cor_matrix, method="circle", type = "upper", cl.pos = "b", tl.pos = "d", tl.cex = 0.6)
Let’s explore some examples. We can see that there is a strong and positive relationship between “rad” (index of accessibility to radial highways) and “tax” (full-value property-tax rate per $10,000). In addition, there is a negtive and strong relationship between “lstat” (lower status of the population (percent)) and “medv” (median value of owner-occupied homes in $1000s).
boston_scaled <- scale(Boston)
summary(boston_scaled)
## crim zn indus
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668
## Median :-0.390280 Median :-0.48724 Median :-0.2109
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202
## chas nox rm age
## Min. :-0.2723 Min. :-1.4644 Min. :-3.8764 Min. :-2.3331
## 1st Qu.:-0.2723 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366
## Median :-0.2723 Median :-0.1441 Median :-0.1084 Median : 0.3171
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.:-0.2723 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059
## Max. : 3.6648 Max. : 2.7296 Max. : 3.5515 Max. : 1.1164
## dis rad tax ptratio
## Min. :-1.2658 Min. :-0.9819 Min. :-1.3127 Min. :-2.7047
## 1st Qu.:-0.8049 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876
## Median :-0.2790 Median :-0.5225 Median :-0.4642 Median : 0.2746
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6617 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058
## Max. : 3.9566 Max. : 1.6596 Max. : 1.7964 Max. : 1.6372
## black lstat medv
## Min. :-3.9033 Min. :-1.5296 Min. :-1.9063
## 1st Qu.: 0.2049 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median : 0.3808 Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.4332 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 0.4406 Max. : 3.5453 Max. : 2.9865
class(boston_scaled)
## [1] "matrix"
boston_scaled <- as.data.frame(boston_scaled)
Creating a categorical variable of the crime rate in the Boston dataset. First, let’s create a quantile vector of crime rate.
bins <- quantile(boston_scaled$crim)
bins
## 0% 25% 50% 75% 100%
## -0.419366929 -0.410563278 -0.390280295 0.007389247 9.924109610
Now, let’s create a categorical variable, and call it, ‘crime’:
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, c(label = "low", "med_low", "med_high", "high"))
table(crime)
## crime
## low med_low med_high high
## 127 126 126 127
Now, let’s remove the original “crim”" from the dataset
boston_scaled <- dplyr::select(boston_scaled, -crim)
And add the new categorical value to scaled data
boston_scaled <- data.frame(boston_scaled, crime)
Dividing the dataset to train and test sets, so that 80% of the data belongs to the train set.
n <- nrow(boston_scaled)
ind <- sample(n, size = n * 0.8)
train <- boston_scaled[ind,]
test <- boston_scaled[-ind,]
correct_classes <- test$crime
test <- dplyr::select(test, -crime)
Use the crime as a target variable and all the other variables as predictors.
lda.fit <- lda(crime ~ ., data = train)
lda.fit
## Call:
## lda(crime ~ ., data = train)
##
## Prior probabilities of groups:
## low med_low med_high high
## 0.2425743 0.2475248 0.2549505 0.2549505
##
## Group means:
## zn indus chas nox rm
## low 0.8738901 -0.8974583 -0.071456607 -0.8852769 0.3688227
## med_low -0.1127084 -0.2809154 0.003267949 -0.5622831 -0.1158019
## med_high -0.3773415 0.1921577 0.071689400 0.4113317 0.1105528
## high -0.4872402 1.0170891 -0.119431971 1.0399658 -0.3863412
## age dis rad tax ptratio
## low -0.8893100 0.8172347 -0.6830354 -0.7424175 -0.422512835
## med_low -0.3018559 0.3494348 -0.5477507 -0.4470063 -0.003941714
## med_high 0.4462700 -0.3657065 -0.4076377 -0.3010156 -0.331495417
## high 0.8126991 -0.8715363 1.6384176 1.5142626 0.781113578
## black lstat medv
## low 0.38298362 -0.72641147 0.44899335
## med_low 0.31496261 -0.11165892 -0.02498681
## med_high 0.08519867 -0.04740194 0.17515111
## high -0.81330145 0.89390654 -0.67684776
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## zn 0.13497819 0.636804742 -0.99191549
## indus 0.01874516 -0.397110369 0.17434722
## chas -0.01504716 0.040628075 0.16892374
## nox 0.43756953 -0.792413542 -1.19409903
## rm 0.03142982 -0.069805285 -0.08944692
## age 0.27572113 -0.494435411 -0.05866500
## dis -0.07725345 -0.395629469 0.26997267
## rad 3.17470222 0.777476587 -0.40551909
## tax -0.03982591 0.219629786 0.78239173
## ptratio 0.13510805 -0.006898625 -0.10993219
## black -0.11793010 0.018541782 0.08538876
## lstat 0.15935078 -0.071577781 0.53951334
## medv 0.05595666 -0.381757587 -0.04065595
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9475 0.0400 0.0124
Drawing the LDA (bi)plot. But first let’s create a numeric vector of the train sets crime classes.
classes <- as.numeric(train$crime)
Now we’re ready to draw the LDA plot.
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
plot(lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 3)
In part 4, categorical crime variable has already been removed from the test dataset, and we have now the test data and correct class labels. Now, we predict the classes with the LDA model on the test data.
lda.pred <- predict(lda.fit, newdata = test)
Cross tabulating the results by creating a table of the correct classes and the predicted ones.
table(correct = correct_classes, predicted = lda.pred$class)
## predicted
## correct low med_low med_high high
## low 20 7 2 0
## med_low 6 18 2 0
## med_high 0 9 13 1
## high 0 0 0 24
The table above reveals that in most cases the crime rates have been predicted correctly, but there are some inconsistencies between the predicted results and correct ones. It seems that the class, high (crime rates), is the most precisely predicted one.
First, reloading and standardizing the dataset.
data('Boston')
boston_scaled <- scale(Boston)
boston_scaled <- as.data.frame(boston_scaled)
Now, let’s use dist() function to calculate the distances between observation using the most common distance measure, which is Euclidean distance.
dist_eu <- dist(Boston)
summary (dist_eu)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 1.119 85.624 170.539 226.315 371.950 626.047
Now, let’s use manhattan distance matrix, another distance measure.
dist_man <- dist(Boston, method = "manhattan")
summary(dist_man)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 2.016 149.145 279.505 342.899 509.707 1198.265
Now, we investigate the optimal number of clusters, using K-means clustering. First, we run K-means algorithm on the data.
km <-kmeans(Boston, centers = 4)
pairs(Boston, col = km$cluster)
Now, we investigate the optimal number of clusters using K-means clustering, with 10 clusters. One way to specify the number of clusters is to look at how the total of within cluster sum of squares (WCSS) behaves when the number of cluster changes. So, let’s look at the behavior of WCSS and plot it.
set.seed(123)
k_max <- 10
twcss <- sapply(1:k_max, function(k){kmeans(Boston, k)$tot.withinss})
qplot(x = 1:k_max, y = twcss, geom = 'line')
By visualizing the total WCSS as a graph, we can see that two clusters would seem optimal. Becasue, the optimal number of clusters is when the value of total WCSS changes radically.
So, let’s run k-means again with two clusters and then visualize the results.
km <-kmeans(Boston, centers = 2)
pairs(Boston, col = km$cluster)
model_predictors <- dplyr::select(train, -crime)
check the dimensions
dim(model_predictors)
## [1] 404 13
dim(lda.fit$scaling)
## [1] 13 3
matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)
library(plotly)
##
## Attaching package: 'plotly'
## The following object is masked from 'package:MASS':
##
## select
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, col = crime, type= 'scatter3d', mode='markers')
## Warning: 'scatter3d' objects don't have these attributes: 'col'
## Valid attributes include:
## 'type', 'visible', 'showlegend', 'legendgroup', 'opacity', 'name', 'uid', 'ids', 'customdata', 'hoverinfo', 'hoverlabel', 'stream', 'x', 'y', 'z', 'text', 'hovertext', 'mode', 'surfaceaxis', 'surfacecolor', 'projection', 'connectgaps', 'line', 'marker', 'textposition', 'textfont', 'error_x', 'error_y', 'error_z', 'scene', 'xcalendar', 'ycalendar', 'zcalendar', 'idssrc', 'customdatasrc', 'hoverinfosrc', 'xsrc', 'ysrc', 'zsrc', 'textsrc', 'hovertextsrc', 'textpositionsrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule'
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', col = km$cluster)
## Warning: 'scatter3d' objects don't have these attributes: 'col'
## Valid attributes include:
## 'type', 'visible', 'showlegend', 'legendgroup', 'opacity', 'name', 'uid', 'ids', 'customdata', 'hoverinfo', 'hoverlabel', 'stream', 'x', 'y', 'z', 'text', 'hovertext', 'mode', 'surfaceaxis', 'surfacecolor', 'projection', 'connectgaps', 'line', 'marker', 'textposition', 'textfont', 'error_x', 'error_y', 'error_z', 'scene', 'xcalendar', 'ycalendar', 'zcalendar', 'idssrc', 'customdatasrc', 'hoverinfosrc', 'xsrc', 'ysrc', 'zsrc', 'textsrc', 'hovertextsrc', 'textpositionsrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule'